package 题组;

import java.util.Arrays;

/**
 * @author 挚爱之夕
 * @date 2021/9/8 - 09 - 08 - 10:22
 * @Description: 题组
 * @Version: 1.0
 */

//不改变非零数据顺序
public class _004_把0移到数组后面 {
    public static void main(String[] args) {
        int[] a = new int[]{1,0,8,4,0,2,2};
        moveZeroes(a);
    }
    //自己写的，慢
    private static void moveZeroes(int[] nums) {
        int l = 0,r = 0;
        while(l<nums.length&&r<nums.length){
            while(l<nums.length&&nums[l]!=0){
                l++;
            }
            r = l+1;
            while(r<nums.length&&nums[r]==0){
                r++;
            }
            if(l<nums.length&&r<nums.length){
                int temp = nums[l];
                nums[l] = nums[r];
                nums[r] = temp;
            }
        }
        System.out.println(Arrays.toString(nums));
    }
    //双指针：right找非零元素，如果left指向0则right与left指向交换
    private static void moveZeroes1(int[] nums) {
        int n = nums.length, left = 0, right = 0;
        while (right < n) {
            if (nums[right] != 0) {//right指向非零，才考虑是否交换
                if(nums[left]==0)
                swap(nums, left, right);
                left++;//无论交不交换，left都要右移
            }
            right++;//遇到0了，left指向该0，right始终向右
        }
        System.out.println(Arrays.toString(nums));
    }

    private static void swap(int[] nums, int left, int right) {
        int temp = nums[left];
        nums[left] = nums[right];
        nums[right] = temp;
    }
}
